import { SYSTEMTYPE } from "../config";

// let Wi = window;
let Netca = window.NetcaPKI;
/***
 * 获取证书列表
 * certInfo:
 *  AppUsrCertNO: "8e9a885eb9d77cb6962d068dcf2eb329@L21"
    AppUsrCertNO2: "8e9a885eb9d77cb6962d068dcf2eb329@L21"
    Thumbprint: "FF9E85BCB1282D77E19242FC5B46D36CA1FDEEB8"
    Thumbprint256: "E6D0DAF9A5A3E42C03B31B8ED75DAD48F964B639267DA42A2D9014CBE23F1061"
    certClass: 0
    certClassExtValue: ""
    certCode: "MIIEijCCA3KgAwIBAgILEJeLA6LEBhHBJ9MwDQYJKoZIhvcNAQEFBQAwUjELMAkGA1UEBhMCQ04xJDAiBgNVBAoMG05FVENBIENlcnRpZmljYXRlIEF1dGhvcml0eTEdMBsGA1UEAwwUQ0NTIE5FVENBIFQyIFN1YjEgQ0EwHhcNMjAwNTEyMDkzMzA2WhcNMjEwNTEyMDkzMzA2WjBsMQswCQYDVQQGEwJDTjESMBAGA1UECAwJR3Vhbmdkb25nMRowGAYDVQQHDBHmtYvor5XlkZjlt6UyMOi3rzEXMBUGA1UECgwO5rWL6K+V5ZGY5belMjAxFDASBgNVBAMMC+a1i+ivleWRmDIwMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0JYxCTk6IDohGkfMigBc67hc/n3vWM6/6vW8r4+PAGhxHDof9TRlD0s5CsIbaJkSd+o92oz+ryFz4H9n9jhDD4z2zo1VoMM570R9x5JicCMD7umw91XbJMn9DuWROkgrfiDZW49gdGtALN8klkEmk54a80CkIMsFUp/DX9KpiSLxRqFiYx7a5wlFnKXFh2eRsDa3S/si4RLnXhNO6FeGBu15jCPdKmnZ9W+pqmZ3vS8f5x4tRlO+6qF+h5k4vtgkAeGGcfKt7uNQrrm0wnQaUGpTtxFWHqaYuJe+ogv/fLEWhWz5821M/BKXJeE/vVwXKJp7kl/OJYABB107cZQjTwIDAQABo4IBRTCCAUEwHwYDVR0jBBgwFoAUBrkf1Z2yDPHEhHRCwjAl4gnaVtgwHQYDVR0OBBYEFDptNBSa+kqdDMNbSOn0j+p2MbUTMGsGA1UdIARkMGIwYAYKKwYBBAGBkkgOCjBSMFAGCCsGAQUFBwIBFkRodHRwOi8vd3d3LmNuY2EubmV0L2NzL2tub3dsZWRnZS93aGl0ZXBhcGVyL2Nwcy9uZXRDQXRlc3RjZXJ0Y3BzLnBkZjA+BgNVHR8ENzA1MDOgMaAvhi1odHRwOi8vdGVzdC5jbmNhLm5ldC9jcmwvQ0NTTkVUQ0FUMlN1YjFDQS5jcmwwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBsAwNAYKKwYBBAGBkkgBDgQmDCQ4ZTlhODg1ZWI5ZDc3Y2I2OTYyZDA2OGRjZjJlYjMyOUBMMjEwDQYJKoZIhvcNAQEFBQADggEBAIRelcnKSAhWECDkVoCLVXuZaOXP6oBu9HJC6eXvNb/kzM54ki2fb5j+kMPfEqqll+m1n4t3FULS8O4fNeggYj6wDmpVXHvGlRpWz6lLLw1bZn3DG8DZ8axQ2sopOf2A2eirPlvFbC2Kp1F9OYkxP1tyEwof1qVPqofRebN8vADX8Q1h5TMtQlVhD6VIV3mjweOeNGIWAWHfaVX1+kumFA6Dtb+5lRtQd+5IBdxeQ7WDeDHzI+004QcNCJs0aLg3tnlgtqjXrg4KGbiWgTDix/OmEGkeexoGKaXhcn2og6xbiIX5wkXu5iu8J1iVt8XZaXAZ/Kn0TiLEvy0Tw2+7oO4="
    deviceRetryNum: 0
    deviceSn: "F319000040"
    deviceType: 47
    issuer: "C=CN,O=NETCA Certificate Authority,CN=CCS NETCA T2 Sub1 CA"
    issuerC: "CN"
    issuerCN: "CCS NETCA T2 Sub1 CA"
    issuerL: ""
    issuerO: "NETCA Certificate Authority"
    issuerOU: ""
    issuerST: ""
    keyUsage: 3
    netcaEnterpriseidItemsCount: 0
    netcaIdentifyItemsCount: 0
    netcaSubjectUniqueId: ""
    publicKeyAlgorithm: 1
    publicKeyBits: 2048
    publicKeyType: 1
    serialNumber: "10978B03A2C40611C127D3"
    shenzhenSubjectUniqueId: ""
    subject: "C=CN,ST=Guangdong,L=测试员工20路,O=测试员工20,CN=测试员20"
    subjectC: "CN"
    subjectCN: "测试员20"
    subjectEmail: ""
    subjectL: "测试员工20路"
    subjectO: "测试员工20"
    subjectOU: ""
    subjectST: "Guangdong"
    userCertServiceId: "8e9a885eb9d77cb6962d068dcf2eb329@L21"
    validFromDate: "20200512093306Z"
    validToDate: "20210512093306Z"
 */

export const getCertList = (type = 0) => {
  const params = {
    type //1：加密证书 2：签名证书 0：所有证书  //当type为2时，过期的ukey不会反回
  };
  return new Promise((resolve, reject) => {
    Netca.GetCertList(params)
      .Then(async function(res) {
        let certList = res.certInfo.filter(ele => ele.keyUsage === 3) || [];
        certList = await Promise.all(
          certList.map(async ele => {
            const crypt = await getCertInfo(ele.deviceSn, "Encrypt");
            const preThumbprint = await getCertInfo(
              ele.deviceSn,
              "Signature",
              29
            );
            return {
              ...ele,
              signCert: ele.certCode,
              cryptCert: crypt.certCode,
              preThumbprint: preThumbprint.value.split(":")[1]
            };
          })
        );
        resolve(certList);
      })
      .Catch(function(res) {
        this.$message.error(res.msg);
      });
  });
};

/***
 * 获取证书信息   id值只用来拿ukey续期前的Thumbprint 29   preThumbprint   取值为value
 */
export const getCertInfo = (certNumber, type, id = -1) => {
  const selectType = "Device";
  const selectCondition = `IssuerCN~'NETCA' && InValidity='True' && CertType='${type}' && DeviceSN='${certNumber}'`;
  const params = {
    cert: {
      type: selectType,
      condition: selectCondition
    },
    id
  };
  return new Promise((resolve, reject) => {
    Netca.getCertStringAttribute(params)
      .Then(function(res) {
        resolve(res);
      })
      .Catch(function(res) {
        // message.error(res.msg);
      });
  });
};

/**
 * 签名
 * @param cestsn deviceSn
 * @param data  需要签名的值
 * @returns
 */
export const p1Sign = (cestsn, data) => {
  if (SYSTEMTYPE !== "sz") {
    const selectCondition =
      "InValidity='True' && CertType='Signature' && DeviceSN = '" +
      cestsn +
      "'";
    const params = {
      cert: {
        encode: "",
        DeviceSN: cestsn,
        type: "Device",
        condition: selectCondition
      },
      data: {
        text: data
      },
      algo: SYSTEMTYPE === "szscwqc" ? 25 : 4
    };
    return new Promise((resolve, reject) => {
      Netca.sign(params)
        .Then(function(res) {
          resolve(res);
        })
        .Catch(function(res) {
          this.$message.error(res.msg);
          reject(res);
        });
    });
  } else {
    return new Promise((resolve, reject) => {
      // Wi.$_$CurrentObj.callMethod(
      //   'SOF_SignDataBase64',
      //   function (res: any) {
      //     resolve({signValue: res.retVal});
      //   },
      //   undefined,
      //   'string',
      //   [cestsn, data]
      // );
      let res = Wi.SOF_SignDataBase64(cestsn, data);
      resolve({ signValue: res });
    });
  }
};

/**
 * 校验密码
 * @param certsn deviceSn
 * @param type  deviceType
 * @param psw  密码
 * @returns
 */
export const verifyPwd = (certsn, type, psw) => {
  const params = {
    pwd: psw,
    sn: certsn,
    type: type
  };
  return new Promise((resolve, reject) => {
    Netca.verifyKeyPwd(params)
      .Then(function(res) {
        resolve(res);
      })
      .Catch(function(res) {
        this.$message.error(res.msg);
        reject(res);
      });
  });
};

/**
 * 监听设备插入拔出
 * @param _delayTime  //延迟时间，单位是毫秒，默认是0毫秒
 * @returns
 */
export const monitorDevice = (_delayTime = 0) => {
  const params = {
    delayTime: _delayTime //延迟时间，默认为0毫秒
  };
  return new Promise((resolve, reject) => {
    Netca.monitorDevice(params)
      .Then(function(res) {
        resolve(res);
      })
      .Catch(function(res) {
        this.$message.error(res.msg);
      });
  });
};

/**
 * 检验服务是否连接
 * @returns
 */

export const checkServer = () => {
  return new Promise((resolve, reject) => {
    Netca.CheckLocalServerOk()
      .Then(function(res) {
        Netca.getVersionInfo({})
          .Then(resq => {
            resolve(resq);
          })
          .Catch(function(res) {
            this.$message.error(res.msg);
          });
      })
      .Catch(function(res) {
        reject(res);
      });
  });
};

/**
 * 修改密码
 * @param certsn deviceSn
 * @param type  deviceType
 * @param oldPwd  旧密码
 * @param modify_newPwd  新密码
 * @returns
 */
export const modifyKeyPwd = (certsn, type, oldPwd, modify_newPwd) => {
  const params = {
    sn: certsn,
    oldPwd: oldPwd,
    newPwd: modify_newPwd,
    type: parseInt(type)
  };

  return new Promise((resolve, reject) => {
    Netca.modifyKeyPwd(params)
      .Then(function(res) {
        resolve(res);
      })
      .Catch(function(res) {
        this.$message.error(res.msg);
      });
  });
};

/**
 * ukey解锁
 * @param type deviceType
 * @param keyType  publicKeyType
 * @param sn  deviceSn
 * @param newPwd  新密码
 * @returns Promise
 */

export const unlockKeyPwd = (type, keyType, sn, newPwd) => {
  const params = {
    type: parseInt(type),
    unlockPwd: keyType === 8 ? "rockey" : "NETCA2006",
    sn,
    newPwd
  };
  return new Promise((resolve, reject) => {
    Netca.unlockKeyPwd(params)
      .Then(function(res) {
        resolve(res);
      })
      .Catch(function(res) {
        this.$message.error(res.msg);
      });
  });
};

/*****************************北京 ***********************************/

//北京CA获取证书列表
export const getUserList = () => {
  return new Promise((resolve, reject) => {
    let list = Wi.SOF_GetUserList().split("&&&");
    list = list
      .filter(item => item)
      .map(item => {
        return {
          subjectCN: item.split("||")[0],
          deviceSn: item.split("||")[1],
          type: "ca"
        };
      });
    resolve(list);
  });
};

//北京CA获取证书信息
export const getUserInfo = (cert, iType) => {
  return new Promise((resolve, reject) => {
    let resp = Wi.GetSignCert(cert);
    if (resp) {
      resolve(Wi.GetCertBasicinfo(resp, iType));
    } else {
      resolve(resp);
    }
  });
};

//北京CA校验密码
export const verifyPwdCA = (certsn, psw) => {
  return new Promise((resolve, reject) => {
    let res = Wi.VerifyUserPIN(certsn, psw);
    if (res) {
      resolve({ result: 1 });
    } else {
      let result = Wi.GetUserPINRetryCount(certsn);
      resolve({ retrynum: result });
    }
  });
};

//北京CA验签
export const p1SignCA = (certsn, data) => {
  return new Promise((resolve, reject) => {
    // Wi.$_$CurrentObj.SignData(certsn, data, function (res: any) {
    //   resolve(res.retVal);
    // });
    let res = Wi.SOF_SignData(certsn, data);
    resolve(res);
  });
};

//北京CA打开设备
// export const openCardCA = (certsn: string) => {
//   return new Promise((resolve, reject) => {
//     Wi.$_$CurrentObj.callMethod(
//       'SOF_OpenCard',
//       function (res: any) {
//         resolve(res.retVal);
//       },
//       undefined,
//       'string',
//       [certsn]
//     );
//   });
// };

export const ValidateCert = certsn => {
  return new Promise((resolve, reject) => {
    let res = Wi.ValidateCert(certsn);
    resolve(res);
  });
};

//获取证书唯一实体标识
export const getCertEntity = certsn => {
  return new Promise((resolve, reject) => {
    let res = Wi.GetCertEntity(certsn);
    resolve(res);
  });
};

/*
 *获取证书身份证号
 *@param sign_cert:加密证书
 */
export const getCertInfoByOID = sign_cert => {
  return new Promise((resolve, reject) => {
    let res = Wi.SOF_GetCertInfoByOid(sign_cert, "2.16.840.1.113732.2");
    resolve(res);
  });
};

/**
 * 获取签章图片。
 * @param deviceSn USB-Key序列号
 * @returns
 */
export const getCertPicture = deviceSn => {
  return new Promise(async (resolve, reject) => {
    const list = (await getUserList()) || [];
    let userInfo = list.find(ele => ele.deviceSn.split("/")[1] === deviceSn);
    if (userInfo) {
      let res = Wi.GetPic(userInfo.deviceSn.split("/")[0]);
      resolve(res);
    } else {
      resolve("");
    }
  });
};

/***
 * 
  1:"key_Serial", //证书序列号
  2:"Sign_ID", //签名证书ID
  3:"Sign_Cert", //签名证书
  4:"Crypt_Cert", //加密证书
  5:"CA_BDate",  //证书有效期起始时间
  6:"CA_EDate",
  7:"CA_CSP",
 */
//北京CA获取证书信息
export const getCertAllInfo = cert => {
  let obj = {
    key_Serial: cert,
    Sign_ID: cert,
    Sign_Cert: "",
    Crypt_Cert: "",
    CA_BDate: "",
    CA_EDate: "",
    CA_CSP: "",
    subject: "",
    signThumbprint: ""
  };
  return new Promise(async (resolve, reject) => {
    let resp = Wi.GetSignCert(cert);
    if (resp) {
      obj["Sign_Cert"] = resp;
      obj["signThumbprint"] = await getCertEntity(resp);
      obj["Crypt_Cert"] = Wi.SOF_ExportExChangeUserCert(cert);
      obj["CA_BDate"] = Wi.GetCertBasicinfo(resp, 11);
      obj["CA_EDate"] = Wi.GetCertBasicinfo(resp, 12);
      obj["key_Serial"] = Wi.GetCertBasicinfo(resp, 2);

      let arr = { 4: "C", 5: "O", 6: "OU", 8: "CA" };
      for (let o in arr) {
        obj["CA_CSP"] +=
          arr[o] + "=" + Wi.GetCertBasicinfo(resp, o) + (o != "8" ? "," : "");
      }
      let arr2 = [
        { value: 4, label: "C" },
        { value: 16, label: "ST" },
        { value: 18, label: "L" },
        { value: 17, label: "CN" }
      ];
      for (let o in arr2) {
        obj["subject"] +=
          arr2[o].label +
          "=" +
          Wi.GetCertBasicinfo(resp, arr2[o].value) +
          (arr2[o].value != "17" ? "," : "");
        if (arr2[o].value == "17") {
          resolve(obj);
        }
      }
    } else {
      resolve(resp);
    }
  });
};
